# *-* coding:utf-8 *-*

import urllib, urllib2, cookielib
import Image
import ImageEnhance
import ImageFilter
import sys
import re
import time
from pytesser import *

class Oa(object):
    def __init__(self, usr, passwd, oaName):
        self.name = usr
        self.passwd = passwd
        self.oaName =oaName
    #调用图形OCR库识别图形为字符，输入图形文件名，输出识别出的验证码
    def  getverify1(self, name):
            # 二值化
        threshold = 140
        table = []
        for i in range(256):
            if i < threshold:
                table.append(0)
            else:
                table.append(1)

        #由于都是数字
        #对于识别成字母的 采用该表进行修正
        rep={'O':'0',
            'I':'1','L':'1',
            'Z':'2',
            'S':'8'
            };

        #打开图片
        im = Image.open(name)
        #转化到亮度
        imgry = im.convert('L')
        imgry.save('g'+name)
        #二值化
        out = imgry.point(table,'1')
        out.save('b'+name)
        #识别
        text = image_to_string(out)
        #识别对吗
        text = text.strip()
        text = text.upper();

        for r in rep:
            text = text.replace(r,rep[r])

        #out.save(text+'.jpg')
        print '验证码: ', text
        return text


    def login(self):
        #使用cookiejar
        cj = cookielib.LWPCookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        urllib2.install_opener(opener)

        #提取验证码图片写入文件
        ImageUrl = 'http://eip.sc.ctc.com/wps/PA_SCV_Portlet_Login/unauth/randomImgValidateCode.action'
        headers = { 'Accept-Language': 'zh-CN',
                    'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
                    'Host': 'eip.sc.ctc.com',
                    'Connection': 'Keep-Alive'
                    }
        req = urllib2.Request(ImageUrl, headers=headers,)
        pic = opener.open(req)
        content = pic.read()
        with open('1212.jpg', 'wb') as f:
            f.write(content)
        #调用验证函数获得验证码
        VerNum = self.getverify1('1212.jpg')

        #使用验证码进行第一次登录，通过登录获取需要第二次登录的cookie
        login_url = 'http://eip.sc.ctc.com/wps/portal/!ut/p/c5/04_SB8K8xLLM9MSSzPy8xBz9QJ_89PTUFP_SEv0I_SizeGd3Rw8Tcx8DAwsTdwMDTxMnfz8P50BDA19DoHykWbwBDuBoQEB3OMhqvPr9EE4pyMixDEhXVAQAIVqhPA!!/dl3/d3/L3dDaXBBQSEhL3dHb0JKdGchLzREMTZSLUlBUUEhIS8xNTUwMDYwL2xp/'
        post_data = {'userid': self.name, 'password': self.passwd, 'validatecode': VerNum}
        login_data = urllib.urlencode(post_data)
        headers = {'Referer': 'http://eip.sc.ctc.com/wps/portal/!ut/p/c5/04_SB8K8xLLM9MSSzPy8xBz9QJ_89PTUFP_SEv2CdEVFALCPJr8!/',
                    'Accept-Language': 'zh-CN',
                    'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Accept-Encoding': 'gzip, deflate',
                    'Host': 'eip.sc.ctc.com',
                    'Connection': 'Keep-Alive',
                    'Cache-Control': 'no-cache'
                    }
        req = urllib2.Request(login_url, login_data, headers=headers, )
        r = opener.open(req)
        #获取返回内容检查登录是否成功
        # ct = r.read()
        # print ct
        # flag = re.search(r'"successFlag":(.*?),', ct)
        # if flag:
            # print 'Login Successful' if flag.group(1)=='true' else 'Login Fail'
        # else:
            # print 'Login Fail'
            # return 'Login Fail'


        #使用验证码和之前获取的COOKIE进行第二次登录
        login_url = 'http://eip.sc.ctc.com/wps/myportal/!ut/p/c5/0wcA1NLTeQ!!/'
        post_data = {'userid': self.name, 'password': self.passwd, 'validatecode': VerNum}
        login_data = urllib.urlencode(post_data)
        headers = {'Referer': 'http://eip.sc.ctc.com/wps/portal/!ut/p/c5/04_SB8K8xLLM9MSSzPy8xBz9QJ_89PTUFP_SEv2CdEVFALCPJr8!/',
                    'Accept-Language': 'zh-CN',
                    'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Accept-Encoding': 'gzip, deflate',
                    'Host': 'eip.sc.ctc.com',
                    'Connection': 'Keep-Alive',
                    'Cache-Control': 'no-cache'
                    }
        req = urllib2.Request(login_url, login_data, headers=headers, )
        r = opener.open(req)
        #查看cookiejar中保存的cookie
        # for index, cookie in enumerate(cj):
        #     print index, ':', cookie
        #查看跳转后的地址
        reurl = r.geturl()
        return reurl

    def getMail(self):
        self.login()
        url = 'http://mail7.sc.ctc.com/cdmail/%s.nsf/xIn?OpenAgent' % self.oaName
        data = urllib2.urlopen(url).read().decode('gbk', 'ignore')
        #pattern = re.compile(r'''style="word-break:break-all" ><p class='red'>(\S*)</p>.*?window.open\('\./\*/(\S*?)'\);.*?<p class='red'>(.*?)</p>.*?<p class='red'>(.*?)</p>''')
        #content = pattern.findall(data)
        #mailStr = [ (str(x+1)+'.',m, i,l, '  ') for x, (i, l, m) in enumerate(content)]

        #mailStr = [y for x in d for y in x]
        
        #return content
        return data

    def getMailCont(self, offset):
        self.login()
        try:
            mHead ='http://mail7.sc.ctc.com/cdmail/%s.nsf/xIn/' % self.oaName 
            mUrl = mHead + offset
            mCont = urllib2.urlopen(mUrl).read().decode('gbk', 'ignore')
            return mCont
        except:
            return 'No data'
    
    def logData3(self):
        self.login()
        for i in range(100):
            time.sleep(1)
            urllib2.urlopen('http://dataportal.sc.ctc.com:8090/tydic-bi-portal3.0/oalogin')
        print 'Login Complete'
            
    
def main():
    name = 'xxx'
    passwd = 'xxx'
    oaName = 'xxx'
    Yang = Oa(name, passwd, oaName)
    mailList = Yang.getMail()
    # for a, b, c, d in mailList:
        # print a, b, c, d
	
if __name__ == '__main__':
    a = main()